package com.test.springboot.springboot3securitydemo1.auth;

import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Created with IntelliJ IDEA.
 *
 * @author： liuziyang
 * @date： 2024/9/30-12:46
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
public class KaptchaAuthenticationProvider extends DaoAuthenticationProvider {
  private static final Logger LOGGER = LoggerFactory.getLogger(KaptchaAuthenticationProvider.class);

  /**
   * @param authentication the authentication request object.
   * @return
   * @throws AuthenticationException
   */
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    final HttpServletRequest request =
        ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    var kaptcha = request.getParameter("kaptcha");
    var sessionKaptcha = (String) request.getSession().getAttribute("kaptcha");
    if (StringUtils.isNotBlank(kaptcha)
        && StringUtils.isNotBlank(sessionKaptcha)
        && StringUtils.equals(kaptcha, sessionKaptcha)) {
      return super.authenticate(authentication);
    }
    LOGGER.warn("验证码输入错误");
    throw new AuthenticationServiceException("验证码输入错误");
  }
}
